import 'dart:convert';

import 'package:aichat_flutter_wallet/module_common/model/chain_lists_model.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_database/objectbox.dart';
import 'package:lib_database/sp.dart';
import 'package:lib_network/http_manager.dart';
import 'package:lib_network/lib_network.dart';
import 'package:lib_database/src/network.dart';

import '../../kai_print.dart';
import '../mpc_help/chainListTool.dart';
import '../network/http_api.dart';
class HttpChainList {
  bool isLoading = false;
  // 获取 盐 的路径
  Future<String?> getSaltByUrl() async {
    try {
      // var result = await HttpManager().post(API.userMpcSaltIsExist, {});
      // print('result!.data ${result!.data}');
      // print('result. ${result.data['isExist']}');
      // if (result.code != HttpConfig().successCode) {
      //   throw Exception('Get user\'s salt exception.');
      // }
      // if (result.data['isExist'] == false) {
      //   throw Exception('Get user\'s salt exception.');
      // }
      var resp = await HttpManager().post(API.getMpcSalt, {});
      if (resp?.code != HttpConfig().successCode) {
        throw Exception('Get user\'s salt exception.');
      }
      print('resp.data[\'mpcSalt\']  ${resp!.data}');
      return resp.data['mpcSalt'].toString().trim();
    } catch (e) {
      print('getSaltByUrl $e');
      return null;
    }
  }

  // 加载 chan 配置
  Future<bool> loadChainList() async {
    if (isLoading) {
      return false;
    }
    isLoading = true;
    try {
      var resp = await HttpManager().get(API.walletChainsLists, {});
      if (resp!.code != HttpConfig().successCode) {
        throw Exception('Exception in obtaining configuration data');
      }
      var model = ChainListsModel.fromJson(resp!.data);
      final resultList = model.walletConfig;
      if (resultList.length <= 0) {
        throw Exception('Exception in obtaining configuration data');
      }
      resultList.sort((a, b) => a.sort.compareTo(b.sort));
      List<Chain> array = [];
      List<String> tokens = [];
      for (int i = 0; i < resultList.length; i++) {
        ChainConfigObjModel group = resultList[i];
        RegExp pattern = RegExp(
            r'((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}');
        List<String> rpcList = [];
        //  写死 sol 中 存在 这个 地址
        if([95279725].contains(int.parse(group.chainId))){
          rpcList.addAll(['https://api.devnet.solana.com']);
        }
        if([728126428].contains(int.parse(group.chainId))){
          rpcList.addAll(['https://api.shasta.trongrid.io/jsonrpc','https://nile.trongrid.io/jsonrpc']);
        }
        if (Config.staticContainChainId.contains(group.chainId)) {
          rpcList.addAll(Config.staticRPCChain['${group.chainId}']!);
        }
        rpcList.addAll([...group.chainNodes].map((e) {
          return e.rcpUrl;
        }).toList());
        rpcList = rpcList.where((url) => !pattern.hasMatch(url)).toList();
        if(rpcList.isEmpty){
          continue;
        }
        var ChainItem = Chain(
            type: ChainListTool.callBackChainType(int.parse(group.chainId)),
            name: group.chainName.toUpperCase(),
            shortName: group.chainName.toUpperCase(),
            symbol: group.symbol,
            logo: group.icon,
            derivePath: ChainListTool.callbackDerivePath(int.parse(group.chainId)),
            blockExplorerUrl: group.browser,
            evmInfo:
                EVMInfo(chainId: int.parse(group.chainId), rpcList: rpcList));
        if (group.tokens != null) {
          for (int j = 0; j < group.tokens!.length; j++) {
            TokensObjModel item = group.tokens![j];
            if (item.contract_address.length > 0) {
              var js = jsonEncode(item);
              tokens.add(js);
              if (item.symbol.toUpperCase() == 'USDT') {
                if (int.parse(group.chainId) == 97) {
                  continue;
                }
                // 设置 web3 存储 的USDT 合约
                Config.getChainUSDTContract[group.chainId.toString()] =
                    item.contract_address;
              }
            }
          }
        }
        array.add(ChainItem);
      }
      // tokens.sort((a, b) => a['sort'].compareTo(b.sort));
      // 存储代币列表
      await SP().setKeyTokenList(tokens);
      await SP().setKeyChainsList(array);
      await ChainList().setChainsList(array);
      await ChainListTool.setWCChainList(array);
      // 初始化 能使用的 网络
      // 添加 初始化 自定义 的 网络
      ObjectBox().customEVMChainModel.initCustomEVMChain();
      await ObjectBox().nodeInfoModel.initNode();
      isLoading = false;
      return true;
    } catch (e) {
      List<Chain> cacheList = await SP().getKeyChainsList();
      // 异常 就 获取 本地缓存
      await ChainList().setChainsList(cacheList);
      await ChainListTool.setWCChainList(cacheList);
      // 初始化 能使用的 网络
      // 添加 初始化 自定义 的 网络
      ObjectBox().customEVMChainModel.initCustomEVMChain();
      await ObjectBox().nodeInfoModel.initNode();
      isLoading = false;
      return false;
    }
  }
}
